/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-07 19:44:56
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.bean.BpWorkSafetyApplyUserDetailBean;
import com.joysuch.wwyt.bp.bean.safetyworkcert.BpWorkSafetyCertDto;
import com.joysuch.wwyt.bp.entity.BpWorkSafetyCertUser;
import com.joysuch.wwyt.bp.repository.BpJobDao;
import com.joysuch.wwyt.bp.repository.BpWorkSafetyCertUserDao;
import com.joysuch.wwyt.bp.service.BpContractorStaffService;
import com.joysuch.wwyt.bp.service.BpWorkSafetyCertUserService;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.exception.BusinessRestrictionsException;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.edu.repository.EduCertificateDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
@Transactional
public class BpWorkSafetyCertUserServiceImpl implements BpWorkSafetyCertUserService {

    @Autowired
    private BpWorkSafetyCertUserDao dao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpJobDao jobDao;
    @Autowired
    private EduCertificateDao eduCertificateDao;
    @Autowired
    private BpContractorStaffService bpContractorStaffService;

    @Override
    public void delete(Long id) throws BusinessRestrictionsException {
        // 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用。不能删除时将抛出业务异常
        checkBussinessRestrictions(id);
        dao.deleteById(id);
    }

    /**
     * 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用
     */
    private void checkBussinessRestrictions(Long id) throws BusinessRestrictionsException {

    }

    @Override
    public BpWorkSafetyCertUser findById(Long id) {
        return dao.findById(id).get();
    }

    @Override
    public List<BpWorkSafetyApplyUserDetailBean> findUsersByCertTypeAndWorkId(Long workId) {
        Integer count = dao.countOfWorkId(workId);
        if (count != null && count != 0) {
            List<BpWorkSafetyCertUser> users = dao.findByWorkId(workId);
            return PageDataUtils.convertListData(users,
                    new PageDataConvert<BpWorkSafetyApplyUserDetailBean, BpWorkSafetyCertUser>() {

                        @Override
                        public BpWorkSafetyApplyUserDetailBean convert(BpWorkSafetyCertUser f) {
                            // f.getOpUserCode().startsWith("CB")
                            if (f.getUserType() != null && f.getUserType() == 1) {
                                // 承包商用户
                                return findContractorUser(f);
//                            if (f.getOpUserCode().startsWith("RY"))
                            } else {
                                // 系统内部用户
                                return findSystemStaff(f);
                            }
//                        else {
//                            // throw new IllegalStateException("全流程-安全作业证-未知的人员类型");
//                            return findSystemStaff(f);
//                        }
                        }
                    });
        } else {
            return null;
        }

    }

    protected BpWorkSafetyApplyUserDetailBean findSystemStaff(BpWorkSafetyCertUser f) {
        BaseUser user = null;
        if (f.getOpUserCode().startsWith("IN")) {
            user = baseUserDao.findById(Long.parseLong(f.getOpUserCode().split("_")[1])).get();
        } else {
            user = baseUserDao.findById(Long.parseLong(f.getOpUserCode())).get();
        }
        BpWorkSafetyApplyUserDetailBean bean = new BpWorkSafetyApplyUserDetailBean();
        List<Long> longs = JSON.parseArray(f.getOperatorUserCertIdJson(), Long.class);
        List<BpWorkSafetyCertDto> certNames = Lists.newArrayList();
        if (longs != null) {
            for (Long aLong : longs) {
                String certName = eduCertificateDao.getNameById(aLong);
                String certCode = eduCertificateDao.getCodeById(aLong);
                //显示证书名称(编号)
                certNames.add(new BpWorkSafetyCertDto(aLong, certName + "(" + certCode + ")"));
            }
        }
        //操作人类别:0公司人员;1承包商
        bean.setPeopleType(f.getUserType());
        bean.setCertNames(certNames);
        bean.setDepartName(f.getDepartName());
        // 此处是为了兼容前端，前端添加、修改使用了同一套东西
        bean.setId(f.getOpUserCode());
        bean.setOpUserName(user.getRealName());
        // bean.setOpUserId(f.getOpUserCode());
        // 存放岗位
        bean.setUserType(jobDao.findNameById(user.getJob()));
        // bean.setUserType(UserTypes.STAFF.getName());
        return bean;
    }

    protected BpWorkSafetyApplyUserDetailBean findContractorUser(BpWorkSafetyCertUser f) {
        BpWorkSafetyApplyUserDetailBean bean = new BpWorkSafetyApplyUserDetailBean();
        List<Long> longs = JSON.parseArray(f.getOperatorUserCertIdJson(), Long.class);
        List<BpWorkSafetyCertDto> certNames = Lists.newArrayList();
        if (longs != null) {
            for (Long aLong : longs) {
                String certName = eduCertificateDao.getNameById(aLong);
                String certCode = eduCertificateDao.getCodeById(aLong);
                //显示证书名称(编号)
                certNames.add(new BpWorkSafetyCertDto(aLong, certName + "(" + certCode + ")"));
            }
        }
        // 此处是为了兼容前端，前端添加、修改使用了同一套东西
        bean.setId(f.getOpUserCode());
        bean.setOpUserName(bpContractorStaffService.getNameById(Long.valueOf(f.getOpUserCode())));
        bean.setCertNames(certNames);
        bean.setDepartName(f.getDepartName());
        //操作人类别:0公司人员;1承包商
        bean.setPeopleType(f.getUserType());
        // bean.setId(UserTypes.CONTRACTOR.getCode() + "_" + f.getOpUserId());
        // TODO 设置承包商人员信息
        // 此处是为了兼容前端，前端添加、修改使用了同一套东西
        // 必须给前端返回 IN_${user_id形式}
        // bean.setOpUserName(user.getRealName());
        // bean.setOpUserId(f.getOpUserId());
        // bean.setUserType(f.getUserType());
        return bean;
    }

}
